package cn.edu.swu.lms;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtils {
    // 定义统一的图片存储路径
    public static final String IMAGE_BASE_PATH = "D:\\JAVA\\workspace\\demo_4\\image";


    //从URL下载图片并保存到指定路径

    public static void saveImage(String url, String savePath) throws IOException {
        // 确保目录存在
        ensureDirectoryExists(getDirectoryFromPath(savePath));

        URL imageUrl = new URL(url);
        try (InputStream in = imageUrl.openStream();
             FileOutputStream out = new FileOutputStream(savePath)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }
    }


    //检查目录是否存在，不存在则创建

    public static void ensureDirectoryExists(String dirPath) {
        File directory = new File(dirPath);
        if (!directory.exists()) {
            boolean created = directory.mkdirs();
            if (created) {
                System.out.println("目录创建成功: " + dirPath);
            } else {
                System.err.println("目录创建失败: " + dirPath);
            }
        }
    }


    //将下载记录追加到日志文件

    public static void appendLog(String log) {
        try (FileWriter fw = new FileWriter("download_log.txt", true);
             BufferedWriter bw = new BufferedWriter(fw)) {
            String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            bw.write(timestamp + " " + log);
            bw.newLine();
        } catch (IOException e) {
            System.err.println("日志记录失败: " + e.getMessage());
        }
    }


    //从文件路径中提取目录路径

    private static String getDirectoryFromPath(String filePath) {
        int lastSeparator = filePath.lastIndexOf(File.separator);
        if (lastSeparator != -1) {
            return filePath.substring(0, lastSeparator);
        }
        return ".";
    }


    //获取完整的图片保存路径

    public static String getImageSavePath(String fileName) {
        return IMAGE_BASE_PATH + File.separator + fileName;
    }
}